package com.aind.common.interceptor;

import com.aind.common.constant.SessionContant;
import com.aind.user.model.User;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * 登录拦截器(未登录状态跳转到登录页面)
 * Created by lpeng on 2017/2/21.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = Logger.getLogger(LoginInterceptor.class);

    /**
     * 登录拦截器：当用户请求的是‘loginAndRegister’资源可以通过，当用户未登录跳转到登录
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute(SessionContant.SESSION_USER);
        String uri = request.getRequestURI();
        String prefix = uri.split("/")[1];
        if (StringUtils.isNotEmpty(prefix) && "loginAndRegister".equals(prefix)){
            return true;
        }
        if (null == user){
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/jsps/user/login.jsp");
            requestDispatcher.forward(request, response);
            return false;
        }
        return true;
    }
}
